package com.jinunn.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.jinunn.common.result.Result;
import com.jinunn.user.service.UserInfoService;
import com.jinunn.user.utils.ConstantWxPropertiesUtils;
import com.jinunn.user.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信操作接口
 *
 * @author JinDun
 * @date 2021/5/18 12:09
 */
@Controller
@RequestMapping("/api/ucenter/wx")
@Slf4j
public class WeiXinApiController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 1 生成微信扫描二维码
     * @return 生成二维码需要参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result<Map<String,Object>> getLoginParam(){
        try {
            Map<String,Object> map = new HashMap<>(4);
            map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String encode = URLEncoder.encode(ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL, "UTF-8");
            map.put("redirect_uri",encode);
            map.put("state",System.currentTimeMillis()+"");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            log.debug(e.getMessage(),e);
            e.printStackTrace();
            return Result.fail();
        }
    }

    /**
     * 微信扫描后回调的方法
     */
    @GetMapping("callback")
    public Result<Map<String,Object>> callback(String code,String state) {
        Map<String,Object> map = userInfoService.callback(code, state);
        if (map!=null){
            return Result.ok(map);
        }else {
            return Result.fail();
        }
    }
}
